<template>
  <div
      id='wrapper'
      v-loading='loading'
      element-loading-text='拼命加载中'
      element-loading-spinner='el-icon-loading'
  >
    <el-row>
      <el-col :xs='24' :sm='24' :lg='24' class='primary'>项目硬件研发</el-col>
    </el-row>
    <el-row>
      <el-col :xs='24' :sm='24' :lg='24' class='border'></el-col>
    </el-row>
    <div style='padding: 20px'>
      <el-table
          :data='tableData'
          :border='true'
          :header-cell-style="{background: '#42b1e8', color: 'white'}"
          style='width:100%'
      >
        <el-table-column align='center' label='项目分组' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_group' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_group }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='项目名称' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_name' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_name }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='平台' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_platform' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_platform }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='OS' width='150'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_os' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_os }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='产品类型' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_product_type' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_product_type }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='产品形态' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_product_form' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_product_form }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='SOM/COP' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_som_or_cop' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_som_or_cop }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='客户区域' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_customer_region' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_customer_region }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='优先级' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_priority' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_priority }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='Status' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_status' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_status }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='PM' width='200'>
          <template slot-scope="scope">
            <span v-if="scope.row.isEdited">
              <el-select
                  v-model="scope.row.project_pm.chinese_name"
                  filterable
                  clearable
                  remote
                  placeholder="请输入"
                  :remote-method="remoteMethod"
                  :loading="selectLoading"
                  @change='userChange(scope.$index, scope.row, $event, "pm")'

              >
                  <el-option
                      v-for="user in userList"
                      :key="user.value"
                      :label="user.label"
                      :value="user.value"
                  >
                      <span style="float: left">{{ user.label }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ user.value }}</span>
                  </el-option>
                </el-select>
            </span>
            <span v-else>
              {{ scope.row.project_pm.chinese_name}}
            </span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='EE人员' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-select
                  v-model="scope.row.project_ee.chinese_name"
                  filterable
                  clearable
                  remote
                  placeholder="请输入"
                  :remote-method="remoteMethod"
                  :loading="selectLoading"
                  @change='userChange(scope.$index, scope.row, $event, "ee")'

              >
                  <el-option
                      v-for="user in userList"
                      :key="user.value"
                      :label="user.label"
                      :value="user.value"
                  >
                      <span style="float: left">{{ user.label }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ user.value }}</span>
                  </el-option>
                </el-select>
            </span>
            <span v-else>{{scope.row.project_ee.chinese_name }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='软件' width='200'>
          <template slot-scope='scope'>
            <span v-if='scope.row.isEdited'>
              <el-input v-model='scope.row.project_soft_ware' clearable>
              </el-input>
            </span>
            <span v-else>{{ scope.row.project_soft_ware }}</span>
          </template>
        </el-table-column>
        <el-table-column align='center' label='操作' width='200' fixed='right' >
          <template slot-scope='scope'>
            <el-row>
              <el-col :xs='!scope.row.isEdited ? 24 : 8' :sm='!scope.row.isEdited ? 24 : 8'
                      :lg='!scope.row.isEdited ? 24 : 8'>
                <el-button
                    v-if='!scope.row.isEdited'
                    type='primary'
                    round size='mini'
                    @click='editRow(scope.$index,scope.row)'
                >
                  编辑
                </el-button>
              </el-col>
              <el-col :xs='scope.row.isEdited ? 12 : 8' :sm='scope.row.isEdited ? 12 : 8'
                      :lg='scope.row.isEdited ? 12 : 8'>
                <el-button
                    type='success'
                    round
                    size='mini'
                    @click='saveRow(scope.$index,scope.row)'
                    v-if='scope.row.isEdited'
                >
                  保存
                </el-button>
              </el-col>
              <el-col :xs='scope.row.isEdited ? 12 : 8' :sm='scope.row.isEdited ? 12 : 8'
                      :lg='scope.row.isEdited ? 12 : 8'>
                <el-button
                    type='info'
                    round size='mini'
                    @click='removeRowEditStatus(scope.$index, scope.row)'
                    v-if='scope.row.isEdited'
                >
                  取消
                </el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <el-row>
      <el-col :xs='20' :sm='20' :lg='20'>
        <el-pagination
            background
            layout='prev, pager, next, sizes, total'
            :page-size.sync='tableSize'
            :page-sizes='[10, 20, 30, 40, 50, 60]'
            @size-change='tableSizeChange'
            @current-change='tableCurrentChange'
            :current-page.sync='tableCurrent'
            style='text-align: center'
            :total='tableTotal'>
        </el-pagination>
      </el-col>
      <el-col :xs='4' :sm='4' :lg='4' style='padding-right: 20px'>
        <el-button
            type='primary'
            style='float: right;'
            :disabled='addBtnDisabled'
            @click='addRow'
        >
          增加项目
        </el-button>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import http from '@/views/sys/axios';
import lodash from "lodash";

export default {
  data() {
    return {
      tableTotal: 0,
      tableSize: 10,
      tableCurrent: 1,
      tableData: [],
      userMap: {},
      userList: [],
      loading: false,
      selectLoading: false,
      addBtnDisabled: false,
      tmpRows: [],
      oriRows: {},
    };
  },
  methods: {

    tableSizeChange(val) {
      this.getCurrentPageData();
    },

    tableCurrentChange(val) {
      this.getCurrentPageData();
    },

    getHardwareDeploymentData() {
      const params = {
        size: this.tableSize,
        page: this.tableCurrent
      };
      return http.get(`/api/indicator/hardware_deployment`, { params });
    },

    editRow(index, row) {
      row.isEdited = true;
      this.$set(this.tableData, index, row);
      this.oriRows[index] = lodash.cloneDeep(row)
    },

    saveRow(index, row) {
      const project_pm_id = row.project_pm.id
      const project_ee_id = row.project_ee.id
      const project_ee = row.project_ee
      const project_pm = row.project_pm
      const isEdited = row.isEdited
      delete row.project_pm
      delete row.project_ee
      delete row.isEdited
      delete row.update_time
      delete row.create_time
      if (row.isAdd) {
        const isAdd = row.isAdd
        delete row.isAdd
        const data = {
          project_pm_id,
          project_ee_id,
          ...row
        }
        this.addProjectInfo(data, index, isEdited, isAdd, project_pm, project_ee)
      } else {
        const data = {
          project_pm_id,
          project_ee_id,
          ...row
        }
        Object.keys(data).forEach(key => {
          if (typeof data[key] === 'string') {
            data[key] = data[key].trim()
          }
        })
        this.changeProjectInfo(data, index, isEdited, project_pm, project_ee)
      }
    },

    removeRowEditStatus(index, row) {
      if (row.isAdd) {
        this.tableData.splice(index, 1)
        this.addBtnDisabled = false
      } else {
        this.oriRows[index].isEdited = false
        this.$set(this.tableData, index, this.oriRows[index]);
      }
    },

    remoteMethod(query) {
      if (query !== '') {
        this.selectLoading = true;
        this.userList = []
        this.handleUserListResult(query)
      } else {
        this.userList = []
      }
    },

    getUserList(query) {
      return http.get(`/api/account/user/query?name=${query}`)
    },

    updateProject(data) {
      return http.put(`/api/indicator/hardware_deployment`, data);
    },

    addProject(data) {
      return http.post(`/api/indicator/hardware_deployment`, data);
    },

    userChange(index, row, username, userType) {
      if (userType === 'pm') {
        row.project_pm = this.userMap[username]
      }
      if (userType === 'ee') {
        row.project_ee = this.userMap[username]
      }
      this.$set(this.tableData, index, row)
    },

    addRow() {
      let row = {}
      row.isEdited = true
      row.project_group = ''
      row.project_name = ''
      row.project_platform = ''
      row.project_os = ''
      row.project_product_type = ''
      row.project_product_form = ''
      row.project_som_or_cop = ''
      row.project_customer_region = ''
      row.project_priority = ''
      row.project_status = ''
      row.project_pm = {}
      row.project_ee = {}
      row.project_soft_ware = ''
      row.isAdd = true
      this.addBtnDisabled = true
      this.tableData.push(row)
    },

    async handleUserListResult(query) {
      try {
        const { code, user_list } = await this.getUserList(query)
        if(code === 200) {
          this.selectLoading = false
          this.userList = user_list
          user_list.forEach(user => {
            this.userMap[user.value] = {
              id: user.id,
              username: user.value,
              chinese_name: user.label,
            }
          })
        }
      } catch (err) {
        throw new Error(err)
      }
    },

    async changeProjectInfo(projectData, index, isEdited, project_pm, project_ee) {
      try {
        const { success, msg } = await this.updateProject(projectData)
        if (success) {
          this.$message.success(msg)
          await this.getCurrentPageData()
        } else {
          delete projectData.project_pm_id
          delete projectData.project_ee_id
          this.$message.error(msg)
          this.$set(this.tableData, index, {isEdited, project_pm, project_ee, ...projectData})
        }
      } catch (e) {
        this.$message.error('服务器异常')
      }
    },

    async addProjectInfo(projectData, index, isEdited, isAdd, project_pm, project_ee) {
      try {
        const { success, msg } = await this.addProject(projectData)
        if (success) {
          this.$message.success(msg)
          await this.getCurrentPageData()
          this.addBtnDisabled = false
        } else {
          delete projectData.project_pm_id
          delete projectData.project_ee_id
          projectData.isEdited = isEdited
          projectData.isAdd = isAdd
          projectData.project_pm = project_pm
          projectData.project_ee = project_ee
          this.$set(this.tableData, index, projectData)
          this.$message.error(msg)
        }
      } catch (e) {
        this.$message.error('服务器异常')
      }
    },

    async getCurrentPageData() {
      this.loading = true;
      try {
        const { code, data, count } = await this.getHardwareDeploymentData();
        if (code === 200) {
          this.tableData = Object.keys(data).map(key => data[key]);
          this.tableTotal = count;
        }
      } catch (err) {
        throw new Error(err);
      }
      this.loading = false;
    },
  },

  mounted() {
    this.getCurrentPageData();
  }

};
</script>

<style scoped lang='scss'>
@import '../../assets/common/common.scss';

/deep/ .el-table th.gutter {
  display: table-cell !important;
}

/deep/ .el-dialog {
  background-color: #eeeeee;
}

/deep/ .el-divider__text {
  color: #ffffff;
  font-size: 20px;
  font-weight: 600;
  background-color: #e6a23c;
  padding: 6px 16px;
}

/deep/ .el-divider--horizontal {
  margin: 40px 0;
  height: 2px;
}

#wrapper {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;
}

.box {
  display: flex;

  div {
    margin: auto;
  }
}

.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

.toTop {
  position: fixed;
  bottom: 80px;
  right: 25px;
  z-index: 10;
}

.details {
  color: #1890ff;
  text-decoration: underline;
  cursor: pointer;
}

.choose {
  padding: 20px 0;

  .flex-box {
    display: flex;
    flex-wrap: nowrap;

    .flexEl {
      flex: 1;
      margin: auto;
    }

    .text-align {
      text-align: center;
    }

    .el {
      flex: 0 0 90%;
    }
  }

  .time {
    position: absolute;
    top: 20px;
    right: 41%;
    font-size: 14px;
    color: #606266;
  }

  .export {
    position: absolute;
    top: 20px;
    right: 20px;
  }

  .filterOption {
    margin-left: 1.7%;
  }
}

.border {
  box-sizing: content-box;
  height: 0;
  overflow: visible;
  margin-top: 1rem;
  margin-bottom: 1rem;
  border: 0;
  border-top: 1px solid rgba(0, 0, 0, .1);
}

.primary {
  color: #409EFF;
  font-size: 30px;
  margin-top: 20px;
  margin-bottom: 10px;
  font-weight: 400;
}

.bgColor {
  background: #fff;
}

.pad {
  padding: 0 20px;
  padding-top: 20px;
}

.marT {
  margin-top: 20px;
}

.btn-group {
  text-align: right;
}

.mar {
  margin: 0 20px;
  margin-top: 20px;
}

.table {
  padding-bottom: 10px;
}
</style>
